package com.jnevision.menu.controller;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jnevision.menu.model.Menu;
import com.jnevision.menu.service.MenuServiceImpl;
import com.jnevision.util.DateUtil;

/**
 * <p>
 * 系统功能-菜单 前端控制器
 * </p>
 *
 * @author gavin
 * @since 2019-07-13
 */
@RestController
@RequestMapping("/menus")
public class MenuController extends ApiController {
    @Autowired
    private MenuServiceImpl menuServiceImpl;

    @PostMapping
    public R<Boolean> add(@RequestBody Menu menu) {
        menu.setValid(true);
        return this.success(this.menuServiceImpl.save(menu));
    }

    @PutMapping
    public R<Boolean> update(@RequestBody Menu menu) {
        menu.setUpdateTime(DateUtil.getNormalTime());
        return this.success(this.menuServiceImpl.updateById(menu));
    }

    @DeleteMapping
    public R<Boolean> delete(int id) {
        return this.success(this.menuServiceImpl.removeById(id));
    }

    @GetMapping
    public R<Menu> get(int id) {
        return this.success(this.menuServiceImpl.getById(id));
    }

    @GetMapping("/page")
    public R<IPage<Menu>> page(Page<Menu> page, Menu menu) {
        return this.success(this.menuServiceImpl.page(page, new QueryWrapper<Menu>(menu)));
    }

    /**
     * 根据角色查询菜单
     * 
     * @param roleId
     * @return
     */
    @GetMapping("/{roleId}")
    public R<Collection<Menu>> getMenu(@PathVariable int roleId) {
        List<Integer> menuIds = this.menuServiceImpl.getMenu(roleId);

        if (!CollectionUtils.isEmpty(menuIds)) {
            return this.success(this.menuServiceImpl.listByIds(menuIds));
        } else {
            return this.failed("no menu data ...");
        }
    }

    /**
     * 获取菜单本身及所有的下级
     * 
     * @param menuId
     * @return
     */
    public R<List<Menu>> getChildren(int menuId) {
        return this.success(this.menuServiceImpl.getChildren(menuId));
    }
}
